package com.atguigu.educenter.controller;

import com.atguigu.educenter.utils.ConstantWxutils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;

@CrossOrigin
@RequestMapping("/api/ucenter/wx")
@Controller
public class WxApiController {

    @GetMapping("callback")
    public String callBack(String code, String state) {

        System.out.println("code" + code);
        System.out.println("state" + state);
        return "redirect:http://localhost:3000";
    }


    @GetMapping("login")
    public String getWxCode() {

        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxutils.WX_OPEN_REDIRECT_URL;
        try {
            URLEncoder.encode(redirectUrl, "utf-8");
        } catch (Exception e) {

        }


        String url = String.format(
                baseUrl,
                ConstantWxutils.WX_OPEN_APP_ID,
                ConstantWxutils.WX_OPEN_REDIRECT_URL,
                "atguigu"
        );

        return "redirect:" + url;
    }
}
